
// gen一个随机数值串出来
function genRandCode (leng) {
  if (String(typeof leng).toLocaleLowerCase() === 'number') return Math.random().toFixed(leng).toString().replace(/\d\./, '')
  else {
    throw new Error(`收到类型不为数值的参数：${leng} | ${String(typeof leng).toLocaleLowerCase()}。无法产生指定长度随机数`)
  }
}
// gen一个随机字母串出来
function genRandEngCode (leng) {
  let result = ''
  let i = 0
  const tempArr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  if (String(typeof leng).toLocaleLowerCase() === 'number') {
    while (i < leng) {
      let randomNum = ~~(Math.random() * 26)
      result += tempArr[randomNum]
      i++
    }
    return result
  } else {
    throw new Error(`收到类型不为数值的参数：${leng} | ${String(typeof leng).toLocaleLowerCase()}。无法产生指定长度随机数`)
  }
}
/**
 * 截取指定长度的数值字符串
 * @param {string|number} num 要截取的数字基础
 * @param {number} leng 截取长度
 * @return {string} 返回指定长度的数值字符串
 */
function addPreZero (num, leng) {
  let tempStr = ''
  let i = 0
  while (i < leng) {
    tempStr += '0'
    i++
  }
  return (`${tempStr}${num}`).slice(-leng)
}

// 生成uid
$('.id[p-uid]').each((index, item) => {
  let leng = 5
  let rawID = ''
  if ($(item).attr('p-uid')) rawID = $(item).attr('p-uid').replace(/\D/g, '')
  else {
    return
  }
  let resultID = ''
  const rawIDAlt = addPreZero(rawID, leng)
  resultID = sessionStorage.getItem(`pro_id${rawID}`) || `A${genRandEngCode(1)}${genRandCode(1)}${rawIDAlt.substr(0, 4)}${genRandCode(2)}${rawIDAlt.substr(-1)}`
  $(item).text(resultID)
  sessionStorage.setItem(`pro_id${rawID}`, resultID)
})

function getNewMessage () {
  /**
   * 获取最新数据接口 {:U('Chat/update_record')} 返回最新一条或者几条数据  条件 chat_id,record_id(记录id)
   */
  // 程序第一行保证循环获取消息
  setTimeout(getNewMessage, 60000)
  $.toptip('正在准备拉取消息', 'success')
  const recordID = $(`.messageBlock[inori-data-id]:eq(-1)`).attr('inori-data-id')
  const ajaxURL = String($(`#getMessage`).val())
  const phpVar = JSON.parse(window.qudaoData)
  const messageFrom = phpVar.from_user_group_id
  const chatID = phpVar.chat_id
  if (recordID === '' || recordID === undefined) {
    if (/[\d\w\.，。：]/.test($('#messageInput').text())) {
      $.toptip(`检查到输入框存在内容，延后刷新拉取`, 'success')
      throw new Error(`检查到输入框存在内容，延后刷新拉取`)
    }
    $.toptip(`未找到消息id,正在准备刷新页面`, 'success')
    setTimeout(() => {
      location.href = `${location.href}?front_end_not_submit=${Math.random()}`
    }, 1000);
    throw new Error(`未找到消息id`)
  }
  const ajaxData = {
    chat_id: chatID,
    record_id: recordID,
    to_user_group_id: messageFrom
  }
  $.ajax(ajaxURL, {
    method: 'post',
    data: ajaxData,
    beforeSend: () => {
      $.toptip('正在拉取消息', 'success')
    }
  }).fail((err) => {
    $.toptip(`消息拉取失败，请检查网络`, 'error')
  }).done((res) => {
    if (res.code && (String(res.code) !== '1' && String(res.code) !== '2')) {
      // 失败
      $.toptip(`消息拉取失败，服务器返回: ${res.message}`, 'error')
      console.error(`消息拉取失败，服务器返回: ${res.message}`)
    } else if (res.code === undefined) {
      // 失败
      $.toptip(`消息拉取失败，服务器返回未知格式`, 'error')
      console.error(`消息拉取失败，服务器返回: ${res}`)
    }
  }).done((res) => {
    if (String(res.code) === '1') {
      $.toptip(`发现${res.data.length}条新消息，正在处理。。。`, 'success')
      $.each(res.data, (index, item) => {
        const MessageBlockString = genMessageBlockString(item)
        // const MessageBlockString = JSON.stringify(item)
        $('.messageContainer').append(`${MessageBlockString}`)
        // 计算所有对话框的高度，高度*2作为滚动距离，保证滚动到末尾
        let scrollLength = 0
        $('.message_main_block').each((index, item) => {
          scrollLength += $(item).height()
        })
        $('.messageContainer').scrollTop(scrollLength * 10086)
      })
    } else if (String(res.code) === '2') {
      $.toptip(`没有发现新消息`, 'success')
    }
  })
}

function genMessageBlockString (item) {
  const cahtID = item.chat_id
  const fromUser = item.from_user
  const msg = item.msg
  const recordID = item.record_id
  const sendTime = item.send_time
  const spaceTime = item.space_time
  const time = item.time.replace(/:\d\d$/, '')
  const to_user = item.to_user
  const templ = `
    <div class="messageBlock" inori-data-id='${recordID}'>
      <div class="person_logo">
        <div class="name my_name">业</div>
      </div>
      <div class="message_main_block">
        <div class="person_name">业务员昵称</div>
        <div class="person_name anjie_from">炒鸡牛逼贷公司</div>
        <div class="his_name">我</div>
        <div class="message_content">${msg}</div>
        <div class="message_time">${time}</div>
      </div>
    </div>
  `.trim()
  return templ
}

$(document).ready(() => {
  // 还原客户消息
  const dataFromPHP = $($.parseXML(window.chat_lccdc_data))
  debugger
  const kehuName = dataFromPHP.find('kehu_name').text()
  const kehuData = dataFromPHP.find('data').text()
  const kehuLink = dataFromPHP.find('link').text()
  let templList = ``
  // 清除可能存在的多余元素
  $(`#panel_data_container .weui-cell`).each((index, item) => {
    $(item).remove()
  })
  templList += `
    <div class="weui-cell">
      <div class="weui-cell__bd">
        <p>客户姓名</p>
      </div>
      <div class="weui-cell__ft">${kehuName}</div>
    </div>
  `.trim()
  $.each(JSON.parse(kehuData), (index, item) => {
    const conventObj = {
      'kehu_edu':'贷款需求',
      'kehu_plan_point':'预计佣金点数',
      'kehu_shouru_way':'收入方式',
      'danwei_xingzhi':'单位性质',
      'business_lic':'营业执照年限',
      'social_sec':'社保年限',
      'fund_time':'公积金年限',
      'danwei_work_time':'现单位工作时长',
      'pay_way':'工资方式',
      'pay_source':'现单位工资金额',
      'avg_cost':'平均月流水',
      'register':'户籍',
      'kehu_more':'补充说明'
    }
    if (item.name === 'kehu_edu') {
      const templ = `
        <div class="weui-cell">
          <div class="weui-cell__bd">
            <p>${conventObj[item.name]}</p>
          </div>
          <div class="weui-cell__ft">${item.value}万</div>
        </div>
      `.trim()
      templList += templ
    } else if (window.__init_i_am_qudao === true && item.name === 'kehu_plan_point') {
      // 特殊条件不显示
      templList += ''
    } else {
      const templ = `
        <div class="weui-cell">
          <div class="weui-cell__bd">
            <p>${conventObj[item.name]}</p>
          </div>
          <div class="weui-cell__ft">${item.value}</div>
        </div>
      `.trim()
      templList += templ
    }
  })
  // 处理图片链接
  const imgLinkArr = kehuLink.split(',').filter((item)=>{return item !== ''})
  const pb2 = $.photoBrowser({
    items: imgLinkArr
  })
  if (imgLinkArr.length > 0) {
    templList += `
      <div class="weui-cell">
        <div class="weui-cell__bd">
          <p>图片资料</p>
        </div>
        <div class="weui-cell__ft" id='photoViewer'>点击浏览</div>
      </div>
    `.trim()
  }
  $(`#panel_data_container`).append(templList)
  if (imgLinkArr.length > 0) {
    $(`#photoViewer`).on('click', {photoView: pb2}, (evt) =>{
      evt.data.photoView.open()
      // pb2.close()
    })
  }

  // 处理头像文字
  $('.person_logo .name').each((index, item) => {
    $(item).text($(item).text().substr(0,1))
  })
  // 发送信息
  $('#sendMessage').on('click', (evt) => {
    const ajaxURL = String($(`#postMessage`).val())
    // from_user_group_id 我是谁
    // to_user_group_id 谁找我
    // chat_id 在哪里
    const phpVar = JSON.parse(window.qudaoData)
    const messageFrom = phpVar.from_user_group_id
    const messageTo = phpVar.to_user_group_id
    const chatID = phpVar.chat_id
    // 渠道身份id，web_id方面的意思
    let qudaoID = ``
    if ($('[person-id]').length > 0) {
      qudaoID = $('[person-id]:eq(0)').attr('person-id')
    }
    const messageContent = $('#messageInput').text()
    if( messageTo === '' || messageTo === undefined ) {
      $.toptip(`无法获得接收信息的对象`, 'error')
      debugger
      throw new Error(`无法获得接收信息的对象`)
    }
    if( messageContent === '' || messageContent === undefined ) {
      $.toptip(`请先填写消息`, 'error')
      debugger
      throw new Error(`请先填写消息`)
    }
    const ajaxData = {
      from_user: messageFrom,
      to_user: messageTo,
      chat_id: chatID,
      msg: messageContent,
      send_time: Math.round(new Date().getTime()/1000),
      web_id: qudaoID
    }
    $.ajax(ajaxURL, {
      method: 'post',
      data: ajaxData,
      beforeSend: () => {
        $.toptip(`正在发送消息`, 'success')
      }
    }).fail((err) => {
      $.toptip(`消息发送失败，请检查网络`, 'error')
    }).done((res) => {
      if (res.code && String(res.code) !== '1') {
        // 失败
        $.toptip(`消息发送失败，服务器返回: ${res.message}`, 'error')
        console.error(`消息发送失败，服务器返回: ${res.message}`)
      } else if (res.code === undefined) {
        // 失败
        $.toptip(`消息发送失败，服务器返回未知格式`, 'error')
        console.error(`消息发送失败，服务器返回: ${res}`)
      }
    }).done((res) => {
      // 成功
      // 生成聊天框
      const date = new Date()
      const year = date.getFullYear()
      const month = date.getMonth()+1
      const day = date.getDate()
      const hour = date.getHours()
      const minute = date.getMinutes()
      const second = date.getSeconds()
      const messageToName = $(`.qudaoListItem[inori-id='${messageTo}']`).text()
      const dateString = `${year}/${month}/${day} ${hour}:${minute}`
      const toQudaomessageBlockTempl = `
        <div class="messageBlock">
          <div class="person_logo">
            <div class="name common_qudao_name">我</div>
          </div>
          <div class="message_main_block">
            <div class="person_name">我</div>
            <div class="his_name">${messageToName}</div>
            <div class="message_content">${messageContent}</div>
            <div class="message_time">${dateString}</div>
          </div>
        </div>
      `.trim()
      $('.messageContainer').append(toQudaomessageBlockTempl)
      // 计算所有对话框的高度，高度*2作为滚动距离，保证滚动到末尾
      let scrollLength = 0
      $('.message_main_block').each((index, item) => {
        scrollLength += $(item).height()
      })
      $('.messageContainer').scrollTop(scrollLength * 10086)
      // 清除消息框
      $(`#messageInput`).text(null)
    })
  })

  // 选人
  $(`#choseAnother`).on('click', (evt) => {
    const ajaxURL = String($(`#getQudaoList`).val())
    const ajaxData = {
      chat_id: String($(`#getRoomID`).val())
    }

    $.ajax(ajaxURL, {
      method: 'post',
      data: ajaxData,
      beforeSend: () => {
        $.toptip('正在获取用户列表', 'success')
      }
    }).fail((err) => {
      $.toptip('获取用户列表失败，请检查网络', 'error')
      throw err
    }).done((res) => {
      if (res.code && String(res.code) !== '1') {
        // 失败
        $.toptip(`人员列表获取失败，服务器返回: ${res.message}`, 'error')
        console.error(`人员列表获取失败，服务器返回: ${res.message}`)
        throw new Error(`人员列表获取失败，服务器返回: ${res.message}`)
      } else if (res.code === undefined) {
        // 失败
        $.toptip(`人员列表获取失败，服务器返回未知格式`, 'error')
        console.error(`人员列表获取失败，服务器返回: ${res}`)
        throw new Error(`人员列表获取失败，服务器返回: ${res}`)
      } else if (res.data.length === 0) {
        $.toptip(`人员列表获取异常，请在产品页面先选择渠道人员`, 'warning')
        console.error(`人员列表获取异常，请在产品页面先选择渠道人员`)
        throw new Error(`人员列表获取异常，请在产品页面先选择渠道人员`)
      }
    }).done((res) => {
      $.toptip("服务器响应成功，正在处理。。。", 'success')
      // 修改替换渠道列表
      $('#qudaoList').empty()
      let qudaoList = ``
      const peopleList = res.data
      $.each(peopleList, (index, item) => {
        const templ = `
          <div class="weui-cell qudaoListItem" inori-id='${item.to_user_group_id}' inori-name-first='${item.web_name.substr(0,1)}'>
            <div class="weui-cell__bd">
              <p>${item.web_name}</p>
            </div>
            <div class="weui-cell__ft"></div>
          </div>
        `.trim()
        qudaoList += templ
      })
      $('#qudaoList').append(qudaoList)
      // 挂点击事件
      $(`#qudaoList .qudaoListItem`).each((index, item) => {
        $(item).on('click', (evt) => {
          const nameFirst = $(evt.target).closest('.qudaoListItem').attr(`inori-name-first`)
          $(`#choseAnother .send_to_person`).text(`${nameFirst}`)
          $(`#choseAnother input`).val(`${String($(evt.target).closest('.qudaoListItem').attr('inori-id'))}`)
          $.closePopup()
        })
      })
      $('#qudaoListPopup').popup()
    })
  })

  // 定时刷新
})